package com.futuremind.recyclerviewfastscroll;

import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Michal on 04/08/16.
 * Responsible for updating the handle / bubble position when user scrolls the {@link Component}.
 */
public class RecyclerViewScrollListener implements Component.ScrolledListener {

    private final FastScroller scroller;
    List<ScrollerListener> listeners = new ArrayList<>();

    public RecyclerViewScrollListener(FastScroller scroller) {
        this.scroller = scroller;
    }

    public void addScrollerListener(ScrollerListener listener) {
        listeners.add(listener);
    }


    void updateHandlePosition(ListContainer rv) {
        float relativePos = 0;
        ItemSizeProvider itemSizeProvider = (ItemSizeProvider) rv.getItemProvider();
        if (scroller.isVertical()) {
            int offset = rv.getScrollValue(Component.AXIS_Y);
            int extent = rv.getHeight();
            int range = rv.getChildCount() * itemSizeProvider.getItemHeight();
            relativePos = offset / (float) (range - extent);
        } else {
            int offset = rv.getScrollValue(Component.AXIS_X);
            int extent = rv.getWidth();
            int range = rv.getChildCount() * itemSizeProvider.getItemWidth();
            relativePos = offset / (float) (range - extent);
        }

        scroller.setScrollerPosition(relativePos);
        notifyListeners(relativePos);
    }

    public void notifyListeners(float relativePos) {
        for (ScrollerListener listener : listeners) listener.onScroll(relativePos);
    }

    @Override
    public void onContentScrolled(Component component, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
        if (scroller.shouldUpdateHandlePosition()) {
            updateHandlePosition((ListContainer) component);
        }
    }

    public interface ScrollerListener {
        void onScroll(float relativePos);
    }

}
